package cn.wangqi.personal.controller;

import cn.wangqi.personal.common.BaseController;
import cn.wangqi.personal.domain.User;
import cn.wangqi.personal.service.IUserService;
import cn.wangqi.personal.sms.SmsUtil;
import cn.wangqi.personal.util.Page;
import cn.wangqi.personal.util.PageResultModel;
import cn.wangqi.personal.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by admin on 2017/8/14.
 */
@RequestMapping("user")
@Controller
public class UserController extends BaseController{

    Logger logger = Logger.getLogger(UserController.class);

    private static Pattern MOBILEPATTERN = Pattern.compile("^((13[0-9])|(176)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

    private static Pattern EMAILPATTERN = Pattern.compile(("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$"));
    @Resource
    public IUserService userService;

    @RequestMapping("index.html")
    public String user(Model model){
        model.addAttribute("code","user");
        return "user/index";
    }

    @RequestMapping("findUserInfoList.html")
    @ResponseBody
    public String findUserInfoList(User user, Integer currentPage){
        try{
            if(currentPage == null || currentPage < 1){
                currentPage = 1;
            }
            Page page = new Page();
            page.setPageSize(10);
            page.setStart((currentPage - 1) * 10);
            List<User> userList = userService.findUserList(page,user);
            userList.stream().forEach(userInfo -> {
                if (StringUtil.isNotEmpty(userInfo.getPhone())) {
                    userInfo.setPhone(userInfo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
                }
                if(StringUtil.isNotEmpty(userInfo.getQq())){
                    userInfo.setQq(userInfo.getQq().replaceAll("(\\d{2})\\d{2,10}(\\d{2})", "$1*****$2"));
                }
                if(StringUtil.isNotEmpty(userInfo.getWechat())){
                    userInfo.setWechat(userInfo.getWechat().replaceAll("(\\w{2})\\w{2,10}(\\w{2})", "$1*****$2"));
                }
                if(StringUtil.isNotEmpty(userInfo.getMail())){
                    userInfo.setMail(userInfo.getMail().replaceAll("(\\w{2})\\w{2,10}(@(\\w)+((\\.\\w+)+))", "$1*****$2"));
                }
            });

            int count = userService.countUserList(user);
            PageResultModel<User> result = new PageResultModel();
            result.setPageNo(currentPage);
            result.setPageSize(page.getPageSize());
            result.setTotal(count);
            result.setDataList(userList);
            return buildSuccessResponse((Serializable) result);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return this.buildErrorResponse("加载失败");
        }
    }

    @RequestMapping("saveUserInfo.html")
    @ResponseBody
    public String saveUserInfo(User user){
        try{
            checkField(user.getClass(),user,"name","sex","birth","phone",
                    "collageId","majorId","qq","wechat","mail","grade","city");
            if(!isMobileNum(user.getPhone())){
                return this.buildErrorResponse("手机号错误");
            }
            if(!isEmail(user.getMail())){
                return this.buildErrorResponse("邮箱错误");
            }
            User temp = userService.findUserByPhone(user.getPhone());
            if(temp!=null&&!(temp.getPhone()==null||"".equals(temp.getPhone()))){
                return this.buildErrorResponse("该用户已存在");
            }
            userService.saveUser(user);
            String jsonStr = "{\"name\":\""+user.getName()+"\"}";
            SmsUtil.sendSms(jsonStr,user.getPhone());
            return this.buildSuccessResponse();
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return this.buildErrorResponse(e.getMessage());
        }
    }

    /**
     * 判断手机号
     * @param phone
     * @return
     */
    public static boolean isMobileNum(String phone){
        Matcher m = MOBILEPATTERN.matcher(phone);
        return m.matches();
    }

    /**
     * 判断邮箱
     * @param email
     * @return
     */
    public static boolean isEmail(String email){
        Matcher m = EMAILPATTERN.matcher(email);
        return m.matches();
    }

    /**
     * 判断是否为空
     * @param c
     * @param o
     * @param args
     * @throws NoSuchFieldException
     */
    public void checkField(Class c,Object o,String ...args) throws NoSuchFieldException {
        for(String temp:args){
            try {
                Field field = c.getDeclaredField(temp);
                field.setAccessible(true);
                Type type = field.getGenericType();
                Object value= field.get(o);
                String typeName = type.getTypeName();
                if("java.lang.String".equals(typeName)||"java.lang.Integer".equals(typeName)){
                    if(StringUtil.isEmpty(value)){
                        throw new IllegalArgumentException("参数"+temp+"不能为空");
                    }
                }else if ("int".equals(typeName)){
                    if(value.equals(0)){
                        throw new IllegalArgumentException("参数"+temp+"不能为空");
                    }
                }
            } catch (NoSuchFieldException e) {
                logger.error(e.getMessage(),e);
                throw new NoSuchFieldException("属性校验失败");
            } catch (IllegalAccessException e) {
                logger.error(e.getMessage(),e);
                throw new NoSuchFieldException("属性校验失败");
            }
        }
    }
}
